//
//  HMSqliteManager.swift
//  01-FMDB演练
//
//  Created by Apple on 2017/7/17.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import FMDB

let DBPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("Weibo.db")

//  数据库操作工具类
class HMSqliteManager: FMDatabaseQueue {

    static let sharedManager: HMSqliteManager = {
        let manager = HMSqliteManager(path: DBPath)
        manager?.createTables()
        //  static 是类方法，不能调用对象方法
        print(DBPath)
        return manager!
    }()
    
    //  创建表
    private func createTables() {
        let path = Bundle.main.path(forResource: "db.sql", ofType: nil)!
        let sql = try! String(contentsOfFile: path)
        self.inDatabase { (db) in
            let result = db?.executeStatements(sql)
            if result == true {
                print("创表成功")
            } else {
                print("创表失败")
            }
        }
    }
    
    //  根据外界查询sql语句返回数组字典
    func selectDicArray(sql: String) -> [[String: Any]] {
        
        var tempArray = [[String: Any]]()
        self.inDatabase { (db) in
            if let resultSet = db?.executeQuery(sql, withArgumentsIn: nil) {
                while resultSet.next() {
                    var dic = [String: Any]()
                    let colCount = resultSet.columnCount()
                    for i in 0..<colCount {
                        let key = resultSet.columnName(for: i)!
                        let value = resultSet.object(forColumnIndex: i)!
                        dic[key] = value
                    }
                    tempArray.append(dic)
                }
            }
            
        }
        return tempArray
    }
    
    
}
